var onDoubleClick = false;
var gTab;

// single click function
//
function TM_checkClick (event) {
  if (event && event.button == 2) return; // right click
  if (event && event.button == 0 && event.detail > 1) return; // double click (with left button)
  
  var target = event.originalTarget;

  // don't do anything if user click on close tab button , or on any other button on tab or tabbar
  if (target.getAttribute("anonid") == "tmp-close-button" ||
      target.localName == "toolbarbutton")
     return;

  // the fix for bug 216899 will make autoscrolling override contentLoadURL if both are enabled
  // we don't need autoscrolling to override contentLoadURL if user click on tab or tabbar
  if (event.button == 1 && gPref.getBoolPref("middlemouse.contentLoadURL")) {
      if (!event.getPreventDefault()) {
         middleMousePaste(event);
         event.stopPropagation();
      }
      return;
  }

  onDoubleClick = false;

  var aTab = target;
  while ( aTab.localName != "tabs" ) {
    if ( aTab.localName == "tab" )
      break;
    if ( aTab.parentNode )
      aTab = aTab.parentNode;
    else
      return;
  }
  gTab = aTab;

  var clickOutTabs = aTab.localName == "tabs";

  // for tab flip
  if ( !clickOutTabs && event.button == 0 && aTab.hasAttribute("clickOnCurrent") ) {
    aTab.removeAttribute("clickOnCurrent");
    var tabFlip = TMP_getBoolPref(tabxBranch, "tabFlip", false);
    var tabFlipDelay = TMP_getIntPref (tabxBranch, "tabFlipDelay", 250);
    if (tabFlip && !event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey){
      window.setTimeout(function () {
                if (!onDoubleClick) {
                    gBrowser.previousTab(aTab);
                    gBrowser.stopMouseHoverSelect(aTab);
                    content.focus();
                }
      }, tabFlipDelay );
      return;
    }
  }

  var prefName
  /* middle click*/   
  if (event.button == 1)
    prefName = "middle"
  /* shift click*/ 
  else if (event.button == 0 && event.shiftKey && !event.ctrlKey && !event.altKey && !event.metaKey)
    prefName = "shift"
  /* alt click*/ 
  else if (event.button == 0 && event.altKey && !event.ctrlKey && !event.shiftKey && !event.metaKey)
    prefName = "alt"
  /* ctrl click*/ 
  else if (event.button == 0 && (event.ctrlKey && !event.metaKey || !event.ctrlKey && event.metaKey) && !event.shiftKey && !event.altKey)
    prefName = "ctrl"

  TMclickAction(prefName, clickOutTabs, aTab);
}

// Double click function
//
function TM_onTabBarDblClick (e) {
  if ( !e || e.button != 0 || e.ctrlKey || e.shiftKey || e.altKey || e.metaKey )
    return;
  onDoubleClick = true;
  var aTab = e.originalTarget;

  // don't do anything if user click on close tab button , or on any other button on tab or tabbar
  if (aTab.getAttribute("anonid") == "tmp-close-button" ||
      aTab.localName == "toolbarbutton")
     return;

  while ( aTab.localName != "tabs" ) {
    if ( aTab.localName == "tab" )
      break;
    aTab = aTab.parentNode;
  }

  // check if the 2 click was not on the same tab
  // it's look like only problem in 1.0.7
  if (gTab != aTab) {
    gTab = aTab;
    return;
  }
  else
   gTab = null;

  TMclickAction( "dbl", aTab.localName == "tabs", aTab );
}

// call action function from click on tabs or tabbar
//
function TMclickAction ( pref, clickOutTabs, aTab ) {

  if (!pref) return; // just in case we missed something

  var defaultPref = {middleClickTab:2, middleClickTabbar:10, shiftClickTab:5, shiftClickTabbar:0,
                     altClickTab:6, altClickTabbar:0, ctrlClickTab:22, ctrlClickTabbar:0,
                     dblClickTab:0, dblClickTabbar:1};

  pref += clickOutTabs ? "ClickTabbar" : "ClickTab";
  var action = TMP_getIntPref (tabxBranch, pref , defaultPref[pref]);

  switch ( action ) {
    case 0 :
      break;
    case 1 :
      BrowserOpenTab();
      break;
    case 2 :
      // removeTab tab after delay,
      // if the tab is in the middle of selecting or we just add new tab
      // it can caused problem
      function _delayCloseTab(tab){
         var b = tab.parentNode.parentNode.parentNode.parentNode;
         b.closeTab(tab); 
      }
      if (aTab.localName != "tab")
         aTab = gBrowser.mCurrentTab;
      setTimeout(_delayCloseTab, 0, aTab);
      break;
    case 3 :
      gBrowser.duplicateTab(aTab);
      break;
    case 4 :
      gBrowser.reloadTab(aTab);
      break;
    case 5 :
      gBrowser.protectTab(aTab);
      break;
    case 6 :
      gBrowser.lockTab(aTab);
      break;
    case 7 :
      gBrowser.reloadAllTabs(aTab);
      break;
    case 8:
      gBrowser.removeAllTabsBut(aTab);
      break;
    case 9:
      gBrowser.closeAllTabs(aTab);
      break;
    case 10:
      gBrowser.undoRemoveTab();
      break;
    case 11:
      gBrowser.renameTab(aTab);
      break;
    case 12: //taken from tco
      if (SessionSaver && SessionSaver.snapBackTab)
        SessionSaver.snapBackTab(SessionSaver.snapback_noFX, SessionSaver.snapback_willFocus);
      break;
    case 13:
      gBrowser.undoRemoveAllTab();
      break;
    case 14:
      gBrowser.duplicateInWindow(aTab, false);
      break;
    case 15:
      gBrowser.freezeTab(aTab);
      break;
    case 16:
      gBrowser.reloadAllTabsBut(aTab);
      break;
    case 17:
      gBrowser.closeLeftTabs(aTab);
      break;
    case 18:
      gBrowser.closeRightTabs(aTab);
      break;
    case 19:
      gBrowser.reloadLeftTabs(aTab);
      break;
    case 20:
      gBrowser.reloadRightTabs(aTab);
      break;
    case 21: // taken from tco
      if (aTab.localName != "tab")
          aTab = gBrowser.mCurrentTab;
      var href;
      if (window.IeView && window.IeView.ieViewLaunch) {
        href = gBrowser.getBrowserForTab(aTab).currentURI.spec;
        IeView.ieViewLaunch("Internet Explorer.lnk", href);
      }
      else if (window.gIeTab && window.gIeTab.switchTabEngine) {
        if (gBrowser.selectedTab != aTab)
          gBrowser.selectedTab = aTab;
        gIeTab.switchTabEngine(aTab, gIeTab.getBoolPref("ietab.alwaysNewTab", false));
      }
      else if(window.ieview && window.ieview.launch) {
        href = gBrowser.getBrowserForTab(aTab).currentURI.spec;
        ieview.launch(href);
      }
      break;
    case 22:
      gBrowser.SelectToMerge(aTab);
      break;
    case 23:
      dtMergeWindows.mergeWindows();
      break;
    case 24:
      gBrowser.closeGroupTabs(aTab);
      break;
    case 25:
        if (aTab.localName != "tab")
          aTab = gBrowser.mCurrentTab;
        var browserSpecs = gBrowser.getBrowserForTab(aTab).webNavigation;
        if (gIsPlaces)
          PlacesController.showAddBookmarkUI(browserSpecs.currentURI);
        else {
          if (BookmarksUtils.addBookmarkForBrowser)
            BookmarksUtils.addBookmarkForBrowser(browserSpecs);
          else if (addBookmarkForBrowser)
            addBookmarkForBrowser(browserSpecs);
        }
        break;
    case 26:// Bookmark All Tabs... (only in firefox)
        if (document.getElementById('Browser:BookmarkAllTabs')) {
          if (gIsPlaces)
            BrowserController.doCommand('Browser:BookmarkAllTabs');
          else
            addBookmarkForTabBrowser(gBrowser, true);
        }
        break;
    case 27:
      gBrowser.duplicateInWindow(aTab, true);
      break;
    case 28:
      gBrowser.copyTabUrl(aTab);
      break;
  }
}

function Tm_checkTabClick(event) {
   var tabContextMenu = window.gBrowser.mStrip.firstChild.nextSibling;
   if (event.originalTarget != tabContextMenu)
     return true;

   var item;
   if (document.popupNode.parentNode)
      item = document.popupNode.parentNode.parentNode.id;
   if (item && (item == "btn_tabslist" || item == "btn_tabslistSorted"))
      gBrowser.mContextTab = document.popupNode.tab;

   var clickOutTabs = gBrowser.mContextTab ? gBrowser.mContextTab.localName == "tabs": true;
   var aTab = clickOutTabs ? gBrowser.mCurrentTab : gBrowser.mContextTab;

   var cIndex = aTab._tPos;
   var isOneWindow = numberOfWindows() == 1;

   var newTab = document.getElementById("tm-newtab")
   TMP_showItem(newTab, tabxPrefs.getBoolPref("newTabMenu"));
   if (clickOutTabs) {
      TMP_setItem(newTab, "label", newTab.getAttribute("_newtab"));
      TMP_setItem(newTab, "oncommand", "TMP_BrowserOpenTab();");
   }
   else {
      TMP_setItem(newTab, "label", newTab.getAttribute("_newtab") + "  " + newTab.getAttribute("_afterthis"));
      TMP_setItem(newTab, "oncommand", "var tabbrowser = this.parentNode.parentNode.parentNode.parentNode; TMP_BrowserOpenTab(tabbrowser.mContextTab);");
   }

   // Duplicate Commands
   TMP_showItem("tm-duplicateTab", tabxPrefs.getBoolPref("duplicateMenu"));
   TMP_showItem("tm-duplicateinWin", tabxPrefs.getBoolPref("duplicateinWinMenu") && !gSingleWindowMode);
   TMP_showItem("tm-detachTab", tabxPrefs.getBoolPref("detachTabMenu") && !gSingleWindowMode);

   TMP_showItem("tm-mergeWindowsTab", tabxPrefs.getBoolPref("showMergeWindow") && (!gSingleWindowMode || (gSingleWindowMode && !isOneWindow)));
   TMP_showItem("tm-renameTab", tabxPrefs.getBoolPref("renameTabMenu"));
   TMP_showItem("tm-copyTabUrl", tabxPrefs.getBoolPref("copyTabUrlMenu"));

   //  ---------------- menuseparator ---------------- //

   // Reload Commands
   TMP_showItem("tm-reloadTab", tabxPrefs.getBoolPref("reloadTabMenu"));
   TMP_showItem("tm-reloadAllTabs", tabxPrefs.getBoolPref("reloadAllMenu"));
   TMP_showItem("tm-autoreloadTab_menu", tabxPrefs.getBoolPref("autoReloadMenu"));
   TMP_showItem("tm-reloadRight", tabxPrefs.getBoolPref("reloadRightMenu"));
   TMP_showItem("tm-reloadLeft", tabxPrefs.getBoolPref("reloadLeftMenu"));
   TMP_showItem("tm-reloadOther", tabxPrefs.getBoolPref("reloadOtherMenu"));

   //  ---------------- menuseparator ---------------- //

   // Undo close tab Commands
   var undoClose = gPref.getBoolPref("extensions.tabmix.undoClose");
   TMP_showItem("tm-undoCloseTab", tabxPrefs.getBoolPref("undoCloseTabMenu") && undoClose);
   TMP_showItem("tm-undoCloseList", tabxPrefs.getBoolPref("undoCloseListMenu") && undoClose);

   //  ---------------- menuseparator ---------------- //

   // Close tab Commands
   TMP_showItem("tm-removeTab", tabxPrefs.getBoolPref("closeTabMenu"));
   TMP_showItem("tm-closeAllTabs", tabxPrefs.getBoolPref("closeAllMenu"));
   TMP_showItem("tm-closeSimilar", tabxPrefs.getBoolPref("closeSimilarTabs"));
   TMP_showItem("tm-removeAllTabsBut", tabxPrefs.getBoolPref("closeOtherMenu"));
   TMP_showItem("tm-closeLeftTabs", tabxPrefs.getBoolPref("closeLeftMenu"));
   TMP_showItem("tm-closeRightTabs", tabxPrefs.getBoolPref("closeRightMenu"));

   //  ---------------- menuseparator ---------------- //

   TMP_showItem("tm-docShell", tabxPrefs.getBoolPref("docShellMenu"));
   TMP_showItem("tm-freezeTab", tabxPrefs.getBoolPref("freezeTabMenu"));
   TMP_showItem("tm-protectTab", tabxPrefs.getBoolPref("protectTabMenu"));
   TMP_showItem("tm-lockTab", tabxPrefs.getBoolPref("lockTabMenu"));

   //  ---------------- menuseparator ---------------- //

   TMP_showItem("tm-addBookmarkAs", tabxPrefs.getBoolPref("bookmarkTabMenu"));
   TMP_showItem("tm-bookmarkAllTabs", tabxPrefs.getBoolPref("bookmarkTabsMenu"));

   // we call this again by popupshown to make sure we don't show 2 menuseparator together
   TMP_tabContextMenuShown(event);

   var protectedTab = aTab.hasAttribute("protected");
   var lockedTab = aTab.hasAttribute("locked");

   TMP_setItem("tm-removeTab", "disabled", protectedTab);

   var closeTabsEmpty = gBrowser.closedTabs.length < 1;
   TMP_setItem("tm-undoCloseTab", "disabled", closeTabsEmpty);
   TMP_setItem("tm-undoCloseList", "disabled", closeTabsEmpty);

   TMP_setItem("tm-mergeWindowsTab", "disabled", isOneWindow);

   TMP_setItem("tm-closeRightTabs", "disabled", cIndex == gBrowser.mTabs.length - 1);
   TMP_setItem("tm-closeLeftTabs", "disabled", cIndex == 0);
   TMP_setItem("tm-reloadRight", "disabled", cIndex == gBrowser.mTabs.length - 1);
   TMP_setItem("tm-reloadLeft", "disabled", cIndex == 0);

   TMP_setItem("tm-docShell", "disabled", clickOutTabs);

   var freezeTabMenu = document.getElementById("tm-freezeTab");
   if ( !freezeTabMenu.hidden )
      TMP_setItem(freezeTabMenu, "checked", lockedTab && protectedTab);

   var lockTabMenu = document.getElementById("tm-lockTab");
   if ( !lockTabMenu.hidden )
      TMP_setItem(lockTabMenu, "checked", lockedTab);

   var protectTabMenu = document.getElementById("tm-protectTab");
   if ( !protectTabMenu.hidden )
      TMP_setItem(protectTabMenu, "checked", protectedTab);

   onAutoReloadPopup(false, aTab);
   return true;
}

// don't show 2 menuseparator together
// this function is call by "popupshown" event
// this is only to the case that other extensions popupshowing run after our Tm_checkTabClick
function TMP_tabContextMenuShown(event) {
   var tabContextMenu = window.gBrowser.mStrip.firstChild.nextSibling;
   if (event.originalTarget != tabContextMenu)
     return;
   // don't show 2 menuseparator together
   var hideNextSeparator = true, lastVisible, hideMenu = true;
   for(var mi = tabContextMenu.firstChild; mi; mi = mi.nextSibling) {
      if (mi.localName == "menuseparator") {
         mi.hidden = hideNextSeparator;
         if (!hideNextSeparator) {
            hideNextSeparator = true;
            lastVisible = mi;
         }
      }
      else if(!mi.hidden && !mi.collapsed) {
         hideNextSeparator = false;
         hideMenu = false;
      }
   }

   // hide the last visible menuseparator if it is the last visible in the menu
   if (hideNextSeparator && lastVisible)
      lastVisible.hidden = true;

   // if all the menu are hidden don't show the popup
   if (hideMenu)
      tabContextMenu.hidePopup();
}


// Show/hide one item (specified via name or the item element itself).
function TMP_showItem ( itemOrId, show ) {
   var item = typeof(itemOrId) == "string" ? document.getElementById(itemOrId) : itemOrId;
   if (item) 
      item.hidden = !show;
}

function TMP_setItem(itemOrId, attrib, val) {
   var item = typeof(itemOrId) == "string" ? document.getElementById(itemOrId) : itemOrId;
   if (val == null)
      item.removeAttribute(attrib);
   else if (!item.hasAttribute(attrib) || item.getAttribute(attrib) != val);
      item.setAttribute(attrib, val);
}

function TM_checkContentMenu () {
  try {
    var showFreezeTab = gPref.getBoolPref("extensions.tabmix.freezeTabContent");
    var showLockTab = gPref.getBoolPref("extensions.tabmix.lockTabContent");
    var showProtectTab = gPref.getBoolPref("extensions.tabmix.protectTabContent");
    var showTabsList = gPref.getBoolPref("extensions.tabmix.tabsList");
    var showCloseTab = gPref.getBoolPref("extensions.tabmix.closeTabContent");
    var showUndoCloseTab = gPref.getBoolPref("extensions.tabmix.undoCloseTabContent");
    var showUndoCloseList = gPref.getBoolPref("extensions.tabmix.undoCloseListContent");
    var undoClose = gPref.getBoolPref("extensions.tabmix.undoClose");
    var autohide = gPref.getBoolPref("browser.tabs.autoHide");
    var keeptab = gPref.getBoolPref("extensions.tabmix.keepLastTab");
    var showDuplicateTab = gPref.getBoolPref("extensions.tabmix.duplicateTabContent");
    var showDuplicateWin = gPref.getBoolPref("extensions.tabmix.duplicateWinContent");
    var showDetachTab = gPref.getBoolPref("extensions.tabmix.detachTabContent");
    var showLinkWithHist = gPref.getBoolPref("extensions.tabmix.linkWithHistory");
    var showMerge = gPref.getBoolPref("extensions.tabmix.mergeWindowContent");
    var showOpenHere = gPref.getBoolPref("extensions.tabmix.openLinkHere");
    var showInverseLink = gPref.getBoolPref("extensions.tabmix.openInverseLink");
    var showAutoReload = gPref.getBoolPref("extensions.tabmix.autoReloadContent");
    var bgPref = gPref.getBoolPref("browser.tabs.loadInBackground");
    var isOneWindow = numberOfWindows() == 1;
    }
  catch(e){}

  var tabsListMenu = document.getElementById("tm-tabsList");
  var closeTabMenu = document.getElementById("tm-content-closetab");
  var freezeTabMenu = document.getElementById("tm-content-freezeTab");
  var lockTabMenu = document.getElementById("tm-content-lockTab");
  var protectTabMenu = document.getElementById("tm-content-protectTab");
  var undoCloseTabMenu = document.getElementById("tm-content-undoCloseTab");
  var undoCloseListMenu = document.getElementById("tm-content-undoCloseList");
  var undoCloseSep = document.getElementById("tm-content-undoCloseSep");
  var duplicateTabMenu = document.getElementById("tm-duplicateTabContext");
  var duplicateWinMenu = document.getElementById("tm-duplicateinWinContext");
  var detachTabMenu = document.getElementById("tm-detachTabContext");
  var linkWithHist = document.getElementById("tm-linkWithhistory");
  var mergeMenu = document.getElementById("tm-mergeWindows");
  var miscSep = document.getElementById("tm-content-miscSep");
  var textSep = document.getElementById("tm-content-textSep");
  var openHere = document.getElementById("tm-openlinkhere");
  var inverseLink = document.getElementById("tm-openinverselink");
  var autoReload = document.getElementById("tm-autoreload_menu");

  var contentClick = gContextMenu.onTextInput || gContextMenu.onLink || gContextMenu.onImage;
  var intabmode = (gBrowser.localName == 'tabbrowser' && gBrowser.mTabs.length > 1);
  var focusType = bgPref ? "fg":"bg";
  var closeTabsEmpty = gBrowser.closedTabs.length < 1;
  var protectedTab = gBrowser.mCurrentTab.hasAttribute("protected");
  var lockedTab = gBrowser.mCurrentTab.hasAttribute("locked");

  openHere.hidden = !gContextMenu.onLink || !showOpenHere;
  inverseLink.hidden = !gContextMenu.onLink || !showInverseLink;
  if (!inverseLink.hidden){
    inverseLink.setAttribute("label", inverseLink.getAttribute(focusType+"label"));
    inverseLink.setAttribute("accesskey", inverseLink.getAttribute(focusType+"accesskey"));
  }
  linkWithHist.hidden = !gContextMenu.onLink || !showLinkWithHist;
  closeTabMenu.hidden = !showCloseTab || !intabmode && autohide || !intabmode && keeptab || contentClick;
  closeTabMenu.setAttribute("disabled", protectedTab);
  freezeTabMenu.hidden = !showFreezeTab || contentClick;
  lockTabMenu.hidden = !showLockTab || contentClick;
  lockTabMenu.setAttribute("checked", lockedTab);
  protectTabMenu.hidden = !showProtectTab || contentClick;
  protectTabMenu.setAttribute("checked", protectedTab);
  duplicateTabMenu.hidden = !showDuplicateTab || contentClick;
  detachTabMenu.hidden = !showDetachTab || contentClick || gSingleWindowMode;
  duplicateWinMenu.hidden = !showDuplicateWin || contentClick || gSingleWindowMode;
  freezeTabMenu.setAttribute("checked", protectedTab && lockedTab);
  tabsListMenu.hidden = !showTabsList || contentClick;
  undoCloseTabMenu.hidden = closeTabsEmpty || !showUndoCloseTab || !undoClose || contentClick;
  undoCloseListMenu.hidden = closeTabsEmpty || !showUndoCloseList || !undoClose || contentClick;
  undoCloseSep.hidden = undoCloseTabMenu.hidden && undoCloseListMenu.hidden || gContextMenu.isTextSelected && closeTabMenu.hidden && lockTabMenu.hidden && protectTabMenu.hidden && tabsListMenu.hidden  && freezeTabMenu.hidden;
  mergeMenu.hidden = !showMerge || isOneWindow || contentClick;
  miscSep.hidden = mergeMenu.hidden && closeTabMenu.hidden && duplicateTabMenu.hidden && duplicateWinMenu.hidden && lockTabMenu.hidden && protectTabMenu.hidden && tabsListMenu.hidden  && freezeTabMenu.hidden || gContextMenu.isTextSelected;
  textSep.hidden = !gContextMenu.isTextSelected || mergeMenu.hidden && duplicateTabMenu.hidden && duplicateWinMenu.hidden && closeTabMenu.hidden && lockTabMenu.hidden && protectTabMenu.hidden && tabsListMenu.hidden  && freezeTabMenu.hidden && undoCloseTabMenu.hidden && undoCloseListMenu.hidden;
  autoReload.hidden = !showAutoReload || contentClick || gContextMenu.isTextSelected;

  var hideOpenAllLinks = gPref.getBoolPref("extensions.tabmix.openAllLinks") ?
                  openMultipleLinks(true) : true;
  document.getElementById("tm-openAllLinks").hidden = hideOpenAllLinks;
  onAutoReloadPopup(true);
}

function onAutoReloadPopup(currentTab, aTab) {
  var tab = currentTab ? gBrowser.mCurrentTab : aTab;
  var id = currentTab ? "tm-autoreload" : "tm-autoreloadTab";
  var element = ["1", "2", "3", "4", "5", "6", "7", "8"];
  var time = [5, 15, 30, 60, 2*60, 5*60, 15*60, 30*60];

  if (tab.autoReloadEnabled == null)
    gBrowser.setupAutoReload(tab);

  document.getElementById(id+"_enable").setAttribute("checked", tab.autoReloadEnabled);

  for(var i=0; i<element.length; i++){
    document.getElementById(id+element[i]).setAttribute("checked", "false");

    if (tab.autoReloadTime == time[i])
      document.getElementById(id+element[i]).setAttribute("checked", "true");
  }
}

function openMultipleLinks(check) {
   var focusedWindow = document.commandDispatcher.focusedWindow;
   if (focusedWindow == window)
      focusedWindow = _content;

   var nsISelectionObject = focusedWindow.getSelection();
   var rangeCount = nsISelectionObject.rangeCount;

   var myNodeFilter = {
      acceptNode : function(n) {
         if(n.nodeName == 'A') {
            return NodeFilter.FILTER_ACCEPT;
         }
         else {
            return NodeFilter.FILTER_SKIP;
         }
      }
   };

   if(rangeCount > 0) {
      var range = nsISelectionObject.getRangeAt(0);

      var treeWalker = window._content.document.createTreeWalker(
            range.cloneContents(),
            NodeFilter.SHOW_ELEMENT,
            myNodeFilter,
            true);
      var nextEpisode = treeWalker.nextNode();

      var newTab, firstTab, firstUrl;
      while(nextEpisode != null) {
//         if(nextEpisode.href && nextEpisode.href.indexOf('http') == 0) {
         if(nextEpisode.href) { // might change it to only accept certain protocols like it used to
            if (check)
               return false;
            newTab = gBrowser.addTab(nextEpisode.href);
            if (!firstTab) {
               firstTab = newTab;
               firstUrl = nextEpisode.href;
               gBrowser.TMP_selectNewForegroundTab(firstTab, null, firstUrl);
            }
         }
         nextEpisode = treeWalker.nextNode();
      }
   }
   return true;
}

// Replace Tab Bar updateContextTab function to catch mouse down on tabs
//
function TMupdateContextTab (e) {
   var aTab = e.originalTarget;
   while ( aTab.localName != "tabs" ) {
      if ( aTab.localName == "tab" )
         break;
      aTab = aTab.parentNode;
   }
   this.mContextTab = aTab;
   if ( aTab.localName == "tabs" )
      this.mContextTab = document.popupNode;
}

function checkForCtrlClick (event) {
  if (event.button == 0 && (event.ctrlKey || event.metaKey)) {
    gBrowser.undoRemoveTab();
    if (gBrowser.closedTabs.length > 0)
      event.target.setAttribute("afterctrlclick", true);
  }
}

function isAfterCtrlClick(popup) {
  if (popup.id == "btn_undoclose_menu") popup = popup.parentNode;
  if (popup.getAttribute("afterctrlclick")) {
    popup.removeAttribute("afterctrlclick");
    if (popup.hasAttribute("open")) popup.removeAttribute("open");
    return true;
  }
  return false;
}

function createUndoCloseList (popup) {
  if (isAfterCtrlClick(popup)) return false;
  beforeCommonList(popup);

  // Grab the list of closed tabs
  var ctabs = gBrowser.closedTabs;
  var mi, count;
  for(var i = ctabs.length - 1; i >= 0; i--) {
    var tab = ctabs[i];
    var tabSH = tab[1];   // Grab the session history for the tab
    // Grab the title and uri (make the uri friendly text)
    var title = tab[2];
    var uri, _uri = tabSH.getEntryAtIndex(tabSH.index, false).URI;
    if ( _uri.scheme == "about" && title == "" )
      uri = title = "about:blank";
    else
      try {
         uri = _uri.scheme + ":\/\/" + _uri.hostPort + _uri.path;
      } catch (e) {
         uri = title;
      }
    var label = title ? title : uri;
    // Insert a menu item for each closed tab in the cache
    mi = document.createElement("menuitem");
    mi.setAttribute("class", "menuitem-iconic bookmark-item");
    mi.setAttribute("statustext", uri)
    mi.setAttribute("tooltiptext", label);
    count = (ctabs.length - i) + (ctabs.length - i<10 ? " : " : ": ");
    mi.setAttribute("label", count + label);
    mi.setAttribute("image", tab[3]);
    mi.setAttribute("accesskey", "" + (ctabs.length - i));
    mi.closeTabIndex = i;
    popup.appendChild(mi);
  }

  var stringBundle = document.getElementById("tmp-string-bundle");
  mi = document.createElement("menuseparator");
  popup.appendChild(mi);
  mi = document.createElement("menuitem");
  mi.setAttribute("label", stringBundle.getString("undoclosetab.clear.label"));
  mi.setAttribute("accesskey", stringBundle.getString("undoclosetab.clear.accesskey"));
  mi.closeTabIndex = -1;
  popup.appendChild(mi);
  mi = document.createElement("menuitem");
  mi.setAttribute("label", stringBundle.getString("restoreall.label"));
  mi.setAttribute("accesskey", stringBundle.getString("restoreall.accesskey"));
  mi.closeTabIndex = -2;
  popup.appendChild(mi);

  return true;
}

function removeCloseTab (event, popup) {
  if (!tabxPrefs.getBoolPref("middleclickDelete")) return;
  var index = event.originalTarget.closeTabIndex
  if (event.button == 1 && index > -1 ){
    getClosedTab('delete', index);
    if (gBrowser.closedTabs.length > 0)
      createUndoCloseList(popup);
    else {
      popup.hidePopup();
      if (popup.parentNode.id != "btn_undoclose")
        popup.parentNode.parentNode.hidePopup();
    }
  }
}

// sometimes context popup stay "open", we hide it manually.
function TM_hidePopup () {
   var node = document.popupNode;
   while (node && node.localName != "menubar" && node.localName != "toolbar") {
      if (node.localName == "menupopup" || node.localName == "popup") {
         if (node.hasAttribute("open")) node.removeAttribute("open");
         node.hidePopup();
      }
      node = node.parentNode;
   }
}

// return the indexd tab from the list and remove the tab from the list
function getClosedTab(where, index) {
   var ctabs = gBrowser.closedTabs;
   var aTab = null;
   var updateRDF = SessionManager.enableBackup && SessionPref.getBoolPref("save.closedtabs");
   if(index >= 0) {
      TMP_SessionStore.removeClosedTab(ctabs.length - 1 - index);
      aTab = ctabs.splice(index, 1)[0];
      var ord=-1;
      switch (where) { // xxx need more work on this. when tab added and removed
         case "current": ord = gBrowser.mCurrentTab._tPos;
            break;
         case "tab":
            if (gPref.getBoolPref("extensions.tabmix.openTabNext")) ord = gBrowser.mCurrentTab._tPos+1;
            else ord = gBrowser.mTabs.length;
            break;
         case "original": ord = aTab[0];
            break;
         default:
      }
      // don't change position on delete
      if (ord > -1 && where != "delete") {
         for (var i = index; i < ctabs.length; i++){
            if (ctabs[i][0] >= ord) ctabs[i][0]++;
         }
         if (updateRDF) SessionManager.fixClosedtabTabPos(ord);
      }
   } else {
    if (index == -2) gBrowser.delayUndoRemoveAllTab();
    else if (index == -1) {
      while(ctabs.length > 0) ctabs.pop();
      TMP_SessionStore.removeClosedTab();
      if (updateRDF) SessionManager.deleteWinClosedtabs(gSessionPath[0] + "/" + gBrowser.windowID);
    }
   }
   if(ctabs.length < 1){
      if (document.getElementById("btn_undoclose")) document.getElementById("btn_undoclose").setAttribute("disabled","true");
   }
   if (aTab != null && updateRDF) SessionManager.deleteClosedtabAt(index+1);
   return aTab;
}


function _restoreTab(where, index) {
   // call restoreTab after delay to let the popup menu time to hide
   window.setTimeout( function () { delayRestoreTab(where, index); }, 0 );
}

// restore the tab
function delayRestoreTab(where, index) {
  var ord, aTab = getClosedTab(where, index);
  if (!aTab) return;
  switch (where) {
    case "current":
      var cTab = gBrowser.mCurrentTab;
      ord = cTab._tPos;
      cTab.collapsed = true;
      var restoredTab = gBrowser.restoreTab(ord, aTab[1], aTab[4], aTab[5]);
      if (restoredTab != cTab)
         gBrowser.removeTab(cTab);
      else
         cTab.collapsed = false;
      break;
    case "window":
      var newWindow = window.openDialog( getBrowserURL(), "_blank", "chrome,all,dialog=no");
      newWindow.duplicat = true;
      newWindow.duplicatData = {
         scroll: aTab[5],
         oldHistory: aTab[1],
         prop: aTab[4]
      }
      break;
    case "tab":
      if (gPref.getBoolPref("extensions.tabmix.openTabNext")) ord = gBrowser.mCurrentTab._tPos+1;
      else ord = gBrowser.mTabs.length;
      gBrowser.restoreTab(ord, aTab[1], aTab[4], aTab[5]);
      break;
    case "original":
      gBrowser.restoreTab(aTab[0], aTab[1], aTab[4], aTab[5]);
  }
}

function NW_waitForSessionHistory(event) {
   //try to set zoom factor befor we load content
   setTextZoom(getBrowser().selectedBrowser, window.duplicatData.scroll.split(",")[2])
   waitForSessionHistory(20);
}

//  wait For sessionHistory in new window
function waitForSessionHistory(attempts) {
   var webNav = gBrowser.webNavigation;
   try{ webNav.sessionHistory; } // Test if sessionHistory exists yet
   catch (err) { // webNav.sessionHistory is not yet available, try again later
      if (attempts) window.setTimeout('waitForSessionHistory(' + --attempts + ')', 50);
      return;
   }
   if ((webNav.sessionHistory == null) && attempts){
      window.setTimeout('waitForSessionHistory(' + --attempts + ')', 50);
      return;
   }
   gBrowser.restoreTab(gBrowser.selectedTab._tPos, 
                       window.duplicatData.oldHistory,
                       window.duplicatData.prop,
                       window.duplicatData.scroll);
   delete window.duplicatData;
   if (window.opener && window.opener.needToClose)
      setTimeout(function() {window.opener.close();}, 0);
}

function closeTabAddBookmarks(currentIndex) {
   var tab = gBrowser.closedTabs[currentIndex];
   var tabSH = tab[1];   // history
   var _URI = tabSH.getEntryAtIndex(tabSH.index, false).URI;
   if (gIsPlaces)
      PlacesController.showAddBookmarkUI(_URI);
   else {
      var url = _URI.spec;
      var title = tab[2];   // title
      if ( gPref.getBoolPref("extensions.tabmix.titlefrombookmark") ) {
         var bookMarkName = getTitleFromBookmark(url);
         if (bookMarkName) title = bookMarkName;
      }
      BookmarksUtils.addBookmark(url, title, undefined);
   }
}

function closeTabcopyTabUrl(currentIndex) {
   var tab = gBrowser.closedTabs[currentIndex];
   var tabSH = tab[1];  // history
   var URL = tabSH.getEntryAtIndex(tabSH.index, false).URI.spec;

   var clipboard = Components.classes["@mozilla.org/widget/clipboardhelper;1"]
                   .getService(Components.interfaces.nsIClipboardHelper);

   clipboard.copyString(URL);
}

function removeTabFromList (event, popup, aType) {
  if (!tabxPrefs.getBoolPref("middleclickDelete"))
    return;

  if (event.target.id == "btn_tabslistSorted")
    return;

  if (event.button == 1) {
    var aTab = event.originalTarget.tab;
    if (popup.parentNode.id == "tm-tabsList" && (gBrowser.mCurrentTab == aTab || gBrowser.isBlankTab(gBrowser.mCurrentTab))) {
         popup.hidePopup();
         gBrowser.removeTab(aTab);
         return;
    }
    gBrowser.removeTab(aTab);
    if (gBrowser.mTabs.length > 0) {
      createTabsList(popup, aType);
      var item = popup.parentNode.parentNode;
      if (item.parentNode.id == "btn_tabslist") createTabsList(item, aType);
    }
    else popup.hidePopup();
  }
}

// called from tabmix.xml tabs scroll buttons
function _createTabsList (event, side) {
   event.stopPropagation();
   var tablist =  document.getElementById("tabslist");

   beforeCommonList(tablist);
   createCommonList(tablist, 2, side);

   if (tablist.hasChildNodes())
      tablist.showPopup(event.target, -1, -1, "popup", "bottomleft","topleft");
}

// show sort/unsort tabs list popup after click on sorted tab menu
function showTabsListPopup (event) {
   event.stopPropagation();
   setTimeout( function (popup){
      popup.showPopup(popup.parentNode, -1, -1, "popup", "bottomleft", "topleft");
   }, 0, event.target.parentNode);
}

function createTabsList (popup, aType) {
  var tabContextMenu = gBrowser.mStrip.firstChild.nextSibling;
  if (popup.hasAttribute("contextmenu") && popup.getAttribute("contextmenu") != tabContextMenu.id)
    popup.setAttribute("contextmenu", tabContextMenu.id);

  beforeCommonList(popup);
  createCommonList(popup, aType);
}

function beforeCommonList(popup) {
  var item = popup.parentNode;
  if (item.id == "btn_tabslist" || item.id == "btn_undoclose")
    item.removeAttribute("tooltiptext");

  // clear out the menu popup if we show the popup after middle click
  while (popup.hasChildNodes()) {
    var menuItem = popup.firstChild;
    if (menuItem.id.indexOf("btn_tabslist") != -1)
      break;
    popup.removeChild(menuItem);
  }

  popup.addEventListener("DOMMenuItemActive", updateMenuItemActive, false);
  popup.addEventListener("DOMMenuItemInactive", updateMenuItemInactive, false);
}

function createCommonList (popup, aType, side) {
  var tabs = new Array(gBrowser.mTabs.length);
  var i;

  switch(aType) {
    case 1:
      for (i = 0; i < gBrowser.mTabs.length; i++)
         tabs[i] = new tabSorting(gBrowser.mTabs[i], i);
      tabs = tabs.sort();
      for (i = 0; i < tabs.length; i++)
         createMenuItems(popup, tabs[i].Tab, tabs[i].Index, aType);
      break;
    case 2:
      for (i = 0; i < gBrowser.mTabs.length; i++) {
         if (side && side == "left" && !gBrowser.mTabs[i].collapsed)
            continue;
         else if (side && side == "right" &&
               (gBrowser.mTabs[i].collapsed || gBrowser.mTabContainer.isTabVisible(gBrowser.mTabs[i]._tPos)))
            continue;
         createMenuItems(popup, gBrowser.mTabs[i], i, aType);
      }
      break;
    case 3:
      for (i = TMP_LastTab.TabHistory.length - 1; i >= 0; i--)
         createMenuItems(popup, TMP_LastTab.TabHistory[i], i, aType);
      break;
  }
}

function createMenuItems(popup, tab, value, aType) {
  var count, mi = document.createElement("menuitem");
  mi.setAttribute("class", "menuitem-iconic bookmark-item alltabs-item");
  mi.setAttribute("statustext", gBrowser.getBrowserForTab(tab).currentURI.spec);
  mi.setAttribute("tooltiptext", tab.label);
  count = aType != 3 ? (value + 1) + (value < 9 ? " : " : ": ") : "";
  mi.setAttribute("count", count);
  mi.setAttribute("label", count + tab.label);
  mi.setAttribute("crop", tab.getAttribute("crop"));
  mi.setAttribute("image", tab.getAttribute("image"));

  if (tab.hasAttribute("busy"))
    mi.setAttribute("busy", tab.getAttribute("busy"));
  if (tab.selected)
     mi.setAttribute("selected", "true");

  mi.value = value;
  tab.mCorrespondingMenuitem = mi;
  tab.addEventListener("DOMAttrModified", TMP_tabOnAttrModified, false);
  tab.addEventListener("TabClose", TMP_tabOnTabClose, false);
  mi.tab = tab;

  if (popup.id == "btn_tabslist_menu")
    popup.insertBefore(mi, document.getElementById("btn_tabslist_sep"));
  else
    popup.appendChild(mi);
}

function TMP_tabOnAttrModified(aEvent) {
  var menuItem = aEvent.target.mCorrespondingMenuitem;
  if (menuItem) {
    var attrName = aEvent.attrName;
    var count = "";
    switch (attrName) {
      case "label":
        count = menuItem.getAttribute("count");
      case "crop":
      case "busy":
      case "image":
      case "selected":
        if (aEvent.attrChange == aEvent.REMOVAL)
          menuItem.removeAttribute(attrName);
        else
          menuItem.setAttribute(attrName, count + aEvent.newValue);
    }
  }
}

function TMP_tabOnTabClose(aEvent) {
   var menuItem = aEvent.target.mCorrespondingMenuitem;
   if (menuItem)
      menuItem.parentNode.removeChild(menuItem);
}

function TMP_TabsListOncommand(event) {
   gBrowser.selectedTab = event.originalTarget.tab;
   gBrowser.mTabContainer.ensureTabIsVisible(gBrowser.selectedTab._tPos);
}

var gBackupLabel = "";
function hideCommonList(popup) {
  // clear out the menu popup and remove the listeners
  while (popup.hasChildNodes()) {
    var menuItem = popup.firstChild;
    if (menuItem.id.indexOf("btn_tabslist") != -1)
      break;
    if ("tab" in menuItem) {
      menuItem.tab.removeEventListener("DOMAttrModified", TMP_tabOnAttrModified, false);
      menuItem.tab.removeEventListener("TabClose", TMP_tabOnTabClose, false);
      menuItem.tab.mCorrespondingMenuitem = null;
    }
    popup.removeChild(menuItem);
  }

  var item = popup.parentNode;
  if (item.id == "btn_tabslist" || item.id == "btn_undoclose")
    item.setAttribute('tooltiptext', item.getAttribute('_tooltiptext'));

  popup.removeEventListener("DOMMenuItemActive", updateMenuItemActive, false);
  popup.removeEventListener("DOMMenuItemInactive", updateMenuItemInactive, false);

  gBackupLabel = "";
}

function updateMenuItemActive(event, tab) {
   var statusTextFld = document.getElementById("statusbar-display");
   if (gBackupLabel=="") gBackupLabel = statusTextFld.label;
   if (!tab) tab = event.target;
   updateStatusText(tab.getAttribute("statustext"));
}

function updateMenuItemInactive(event) {
   updateStatusText("");
}

function updateStatusText(itemText) {
   var statusTextFld = document.getElementById("statusbar-display");
   var newText = itemText ? itemText : gBackupLabel;
   if (newText != statusTextFld.label)
      statusTextFld.label = newText;
}

function tabSorting(tab, index) {
   this.Tab = tab;
   this.Index = index;
}

tabSorting.prototype.toString = function() { return this.Tab.label.toLowerCase(); }
